//
//  SYDLoginViewController.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/8/5.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDLoginViewController.h"

@interface SYDLoginViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView *phoneView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;//登录
@property (weak, nonatomic) IBOutlet UIButton *forgetBtn;//忘记密码
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;//注册
@property (weak, nonatomic) IBOutlet UIImageView *icon_header;
//iphone_x 适配约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headetImageConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;

@end


@implementation SYDLoginViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    
    [self initLoginUI];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.hidden = YES;
    self.navigationBar.hidden = YES;
    
//    [self generateData];
    
}
-(void)initLoginUI{
    if (iPhone8_X) {
        self.headetImageConstraint.constant = 123;
        self.bottomConstraint.constant = 87;
    } else {
        self.headetImageConstraint.constant = 81;
        self.bottomConstraint.constant = 43;
    }
    self.phoneTextField.text = [YMSaveTool valueForKey:USER_NAME];
    [self.phoneView drawBorderWithColor:GREEN_COLOR radius:20];
    [self.passwordView drawBorderWithColor:GREEN_COLOR radius:20];
    
    [self.loginBtn drawBorderWithColor:GREEN_COLOR radius:20];
//    self.phoneTextField.placeholderColor = LoginTextfieldColor;
//    self.passwordTextField.placeholderColor = LoginTextfieldColor;
    self.phoneTextField.textColor = GREEN_COLOR;
    self.phoneTextField.tag = 10;
    self.passwordTextField.tag = 20;
    [self.icon_header drawCircle:6 borderColor:WHITE_COLOR];
    [self.icon_header sd_setImageWithURL:[NSURL URLWithString:[YMSaveTool valueForKey:@"headImageUrl"]]placeholderImage:[UIImage imageNamed:@"icon_head_portrait1"]];
#pragma mark -- 监听事件(按钮点击)
    self.loginBtn.eventTimeInterval = 3.0;
    [[self.loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        //登录操作
        [self loginAction];
    }];
    self.forgetBtn.eventTimeInterval = 3.0;
    [[self.forgetBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
    
        SYDForgetWordViewController *forgetVc = [[SYDForgetWordViewController alloc]init];
        [self.navigationController pushViewController:forgetVc animated:YES];
    }];
    self.registerBtn.eventTimeInterval = 3.0;
    [[self.registerBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        SYDRegisterViewController *registerVc = [[SYDRegisterViewController alloc]init];
        [self.navigationController pushViewController:registerVc animated:YES];
    }];
    #pragma mark---监听textfield 输入文字
    if (self.phoneTextField.text.length > 0) {
        [self.phoneTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
            NSLog(@"电话号码:%@",x);
        }];
    }
    [self.phoneTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    if (self.passwordTextField.text.length > 0) {
        [self.passwordTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
            NSLog(@"密码:%@",x);
        }];
    }
    //通知
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardDidShowNotification object:nil]subscribeNext:^(NSNotification * _Nullable x) {
        NSLog(@"键盘弹起");
    }];
}
- (BOOL)textField:(UITextField *)textField1 shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSInteger pointLength = 0;
    if (textField1 == self.phoneTextField) {
        NSInteger existedLength = textField1.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        pointLength = existedLength - selectedLength + replaceLength;
    }
    //超过16位就不能在输入了
    if (pointLength > 12) {
        return NO;
    }else{
        return YES;
    }
    
}
//然后实现方法：
- (void)textFieldDidChange:(UITextField *)textField
{
    int length = 11;//限制的字数
    NSString *toBeString = textField.text;
    NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage;// 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];       //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position || !selectedRange)
        {
            if (toBeString.length > length)
            {
                NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:length];
                if (rangeIndex.length == 1)
                {
                    textField.text = [toBeString substringToIndex:length];
                }
                else
                {
                    NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, length)];
                    textField.text = [toBeString substringWithRange:rangeRange];
                }
            }
        }
        
    }
}

-(void)loginAction{

    WEAKSELF
    if (self.phoneTextField.text.length == 0) {
        [SVProgressHUD displayInfoWithStatus:@"请输入手机号"];
    }else if (self.phoneTextField.text.length < 11){
        [SVProgressHUD displayInfoWithStatus:@"手机号格式有误,请重新输入"];
    }else if (![NSString justMobile:self.phoneTextField.text]){
        [SVProgressHUD displayInfoWithStatus:@"手机号格式有误,请重新输入"];
    }else if (self.passwordTextField.text.length == 0){
        [SVProgressHUD displayInfoWithStatus:@"请输入密码"];
    }else{

        [[SYDNetwork shareTool]UserLoginWithPassword:self.passwordTextField.text username:self.phoneTextField.text success:^(NSURLSessionDataTask *task, id responseObject) {
            @try {
                if ([responseObject[@"statusCode"]integerValue] == 200) {
                    SYDAccount *model = [SYDAccount mj_objectWithKeyValues:responseObject[@"obj"]];
                    SYDHomeViewController *homeVc = [[SYDHomeViewController alloc]init];
                    [YMSaveTool setObject:model.cityCode forKey:CityCode];
                    [YMSaveTool setObject:model.userId forKey:USER_ID];
                    [YMSaveTool setObject:model.headImageUrl forKey:@"headImageUrl"];
                    [YMSaveTool setObject:self.phoneTextField.text forKey:USER_NAME];
                    
                    //根据token来进行登录判断
                    [SYDAccountTool saveToken:model.token];
                    [SYDAccountTool saveInvaildDate:model.invaildDate];//
                    
                    [SYDAccountTool saveAccount:model];
                    [weakSelf.navigationController pushViewController:homeVc animated:YES];

                }else{
                    [SVProgressHUD displayInfoWithStatus:responseObject[@"msg"]];
                }
            } @catch (NSException *exception) {
                NSLog(@"exception:%@",exception.description);
            } @finally {
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"error:%@",error);
            [SVProgressHUD displayInfoWithStatus:@"网络不可用,请检查网络"];
        }];
    }
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
